<template>
  <view class="medical-record">
    <view class="tab-wrap">
      <view
        v-for="item in tabList"
        :key="item"
        @tap="changeTab(item)"
        :class="[
          'tab-item',
          currentTab === item
            ? 'active' : 'no-active',
        ]"
      >
        {{ item }}
      </view>
    </view>
    <view v-if="list.length > 0" class="list-wrap">
      <MedicalItems :list="list" />
    </view>
    <view class="empty-wrap" v-else>
      <NoData
        :emptyText="currentTab === '上传的病历' ? '暂无上传的病历' : '暂无就医病历'"
        emptyImage="https://ainengli.meilianshuke.com/jkhx/patient/empty-list.png"
      />
    </view>
    <view v-if="currentTab === '上传的病历'" class="fixedBtn" @tap="showUpload">
      <text class="name">上传病历</text>
    </view>
    <com-popup
      v-if="uploadPopup"
      ref="popup"
      title="选择上传方式"
      :action="false"
      @close="uploadPopup = false"
      bgColor="#F3F7F8"
    >
      <view class="lists">
        <view
          v-for="(item, index) in uploadTypes"
          :key="index"
          class="item"
          @tap="handleUpload(item.type)"
        >
          <image :src="item.icon" class="icon" />
          <text>{{ item.name }}</text>
        </view>
      </view>
    </com-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useStore } from '@/store';
import { aiParse, getOutpatientRecordList } from '@/request/apis/archive';
import MedicalItems from './components/medical-record-items.vue';
import NoData from './components/no-data.vue';
const store = useStore();
const { proxy } : any = getCurrentInstance();
import { upload } from "@/request/apis/file";

const tabList = ref(["上传的病历", "就医病历"]);
const currentTab = ref("上传的病历");
const uploadTypes = ref([
  {
    name: '拍照',
    icon: 'https://ainengli.meilianshuke.com/jkhx/patient/camera.png',
    type: 'camera'
  },
  {
    name: '图片',
    icon: 'https://ainengli.meilianshuke.com/jkhx/patient/images.png',
    type: 'album'
  }
])

const recordType = ref('outpatient_record');
const list = ref([]);
const uploadPopup = ref(false);

const changeTab = (tab: string) => {
  if (tab === currentTab.value) return;
  currentTab.value = tab;
  if (tab === '就医病历') {
    list.value = [];
  }else {
    recordType.value = 'outpatient_record';
    getList();
  }
};

const showUpload = () => {
  uploadPopup.value = !uploadPopup.value
}

const handleUpload = async (type: string) => {
  const options = {
    countResidueFn: () => 5, // 剩余可传数量
    sizeLimit: 20, // 10MB限制
    sourceType: [type], //album 从相册选择,camera 使用相机
    page: { loading: { show: msg => console.log(msg), hide: () => {} } },
    upload: upload // 你的上传方法
  };

  try {
    uploadPopup.value = false;
    const uploadedArr = await proxy.utils.image.uploadImages(options);
    
    if (uploadedArr.length > 0) {
      // 2. 调用业务接口
      uni.showLoading({
				title: '上传中',
        mask: true
      })
      aiParse({ patientId: store.patient.current.id, fileUrls: uploadedArr }).then((res) => {
        console.log(res, 'ai接口调用成功');
        uploadPopup.value = false;
        setTimeout(() => {
          uni.showToast({
            title: 'Al正在努力识别图片，请稍后在列表中查看',
            icon: 'none',
            duration: 2000
          })
        }, 300)
        // uni.showToast({
        //   title: 'Al正在努力识别图片，请稍后在列表中查看',
        //   icon: 'none',
        //   duration: 2000
        // })
        getList();
      }).catch((err) => {
        console.log(err, 'ai接口调用失败');
      }).finally(() => {
        uni.hideLoading();
      });
    }
  } finally {
    options.page?.loading.hide();
  }
};

const getList = () => {
  uni.showLoading({
    title: '加载中'
  })
  getOutpatientRecordList({
    patientId: store.patient.current.id,
    recordType: recordType.value
  }).then(res => {
    list.value = res.records || [];
  }).catch((err) => {
    console.error(err, '失败');
  }).finally(() => {
    uni.hideLoading();
  })
}

onLoad((query) => {
  recordType.value = query.recordType;
  getList();
})
</script>

<style scoped lang="scss">
.medical-record {
  min-height: 100vh;
  background-color: #F3F7F8;
  padding-top: 100rpx;
  padding-bottom: calc(170rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(170rpx + env(safe-area-inset-bottom));
  .tab-wrap {
    overflow-x: scroll;
    display: flex;
    height: 100rpx;
    width: 100vw;
    background: #fff;
    position: fixed;
    top: 0;
    z-index: 10;
    .tab-item {
      padding: 0 30rpx;
      font-size: 28rpx;
      color: #666666;
      // transition: all 0.3s ease-out;
      display: flex;
      align-items: center;
    }
    .tab-item.active {
      color: #222222;
      font-size: 36rpx;
      font-weight: bold;
      position: relative;
      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 40rpx;
        height: 6rpx;
        background-color: #00d1b6;
        transform: translateX(-50%);
        // transition: all 0.3s ease;
        border-radius: 4rpx;
      }
    }
    .tab-item.no-active {
      position: relative;
      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 40rpx;
        height: 6rpx;
        background-color: #fff;
        transform: translateX(-50%);
        // transition: all 0.3s ease;
        border-radius: 4rpx;
      }
    }
  }
  .list-wrap {
    min-height: calc(100vh - 100rpx - 68rpx - constant(safe-area-inset-bottom));
    min-height: calc(100vh - 100rpx - 68rpx - env(safe-area-inset-bottom));
  }
  .empty-wrap {
    height: calc(100vh - 160rpx - constant(safe-area-inset-bottom));
    height: calc(100vh - 160rpx - env(safe-area-inset-bottom));
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .fixedBtn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 24rpx 0;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    color: #fff;
    text-align: center;
    background: #fff;
    // border-top: 1rpx solid #e5e6eb;
    z-index: 10;

    .name {
      display: inline-block;
      width: calc(100% - 60rpx);
      padding: 22rpx 0;
      margin: 0 30rpx;
      font-size: 32rpx;
      font-weight: 600;
      background: #00d1b6;
      border-radius: 50rpx;
    }
  }
}
.lists {
  padding: 16rpx 0;
  padding-bottom: calc(16rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
  background: #F3F7F8;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  .item {
    width: 216rpx;
    height: 216rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 20rpx;
    font-size: 30rpx;
    color: #222222;
    background: #fff;
    border-radius: 32rpx;
    .icon {
      width: 96rpx;
      height: 96rpx;
    }
  }
}
</style>
